<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\UserToken;
use App\Models\LotteryResult;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class CouponController extends Controller
{
    /**
     * 获取用户的优惠券列表
     *
     * @param string $token
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($token)
    {
        try {
            Log::info('开始获取用户优惠券列表', ['token' => $token]);

            // 验证token
            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                Log::warning('无效的访问令牌或已过期', [
                    'token' => $token,
                    'current_time' => Carbon::now()->format('Y-m-d H:i:s')
                ]);
                return response()->json([
                    'code' => 401,
                    'msg' => '访问令牌无效或已过期',
                    'data' => null
                ], 401);
            }

            // 获取用户的优惠券列表
            $coupons = LotteryResult::with([
                    'verificationCode',
                    'verificationCode.codeActivity',
                    'verificationCode.codeActivity.product'
                ])
                ->where('wechat_users_id', $userToken->wechat_user_id)
                ->get()
                ->map(function ($result) {
                    return [
                        'code' => $result->verificationCode->code,
                        'card_number' => $result->verificationCode->card_number,
                        'product_name' => $result->verificationCode->codeActivity->product->name,
                        'value' => $result->verificationCode->codeActivity->value,
                        'status' => $result->verificationCode->is_used,
                        'expired_at' => $result->verificationCode->codeActivity->end_time
                    ];
                });

            // 添加详细的日志记录
            Log::info('用户优惠券列表详情', [
                'wechat_user_id' => $userToken->wechat_user_id,
                'coupon_count' => $coupons->count(),
                'coupons_data' => $coupons->toArray()  // 记录完整的优惠券数据
            ]);

            Log::info('成功获取用户优惠券列表', [
                'wechat_user_id' => $userToken->wechat_user_id,
                'coupon_count' => $coupons->count()
            ]);

            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'coupons' => $coupons,
                    'total' => $coupons->count()
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取用户优惠券列表失败', [
                'token' => $token,
                'error_message' => $e->getMessage(),
                'error_trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'code' => 500,
                'msg' => '获取优惠券列表失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取优惠券详情
     *
     * @param string $token
     * @param int $couponId
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($token, $couponId)
    {
        try {
            Log::info('开始获取优惠券详情', [
                'token' => $token,
                'coupon_id' => $couponId
            ]);

            // 验证token
            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                return response()->json([
                    'code' => 401,
                    'msg' => '访问令牌无效或已过期',
                    'data' => null
                ], 401);
            }

            // 获取优惠券详情
            $coupon = LotteryResult::where('id', $couponId)
                ->where('wechat_users_id', $userToken->wechat_user_id)
                ->with(['product:id,name,image_url,description'])
                ->first();

            if (!$coupon) {
                return response()->json([
                    'code' => 404,
                    'msg' => '优惠券不存在',
                    'data' => null
                ], 404);
            }

            $couponData = [
                'id' => $coupon->id,
                'code' => $coupon->code,
                'product_name' => $coupon->product->name ?? '未知商品',
                'product_image' => $coupon->product->image_url ?? null,
                'product_description' => $coupon->product->description ?? null,
                'status' => $coupon->status,
                'created_at' => $coupon->created_at->format('Y-m-d H:i:s'),
                'expired_at' => $coupon->expired_at ? $coupon->expired_at->format('Y-m-d H:i:s') : null,
                'used_at' => $coupon->used_at ? $coupon->used_at->format('Y-m-d H:i:s') : null
            ];

            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'data' => $couponData
            ]);

        } catch (\Exception $e) {
            Log::error('获取优惠券详情失败', [
                'token' => $token,
                'coupon_id' => $couponId,
                'error_message' => $e->getMessage()
            ]);

            return response()->json([
                'code' => 500,
                'msg' => '获取优惠券详情失败',
                'data' => null
            ], 500);
        }
    }
} 